<template>
  <div class="teamHome">
    <teamName></teamName>
    <van-collapse v-model="activeNames">
      <div class="formItem" v-for="(user, index) in templetArr" :key="index">
        <van-collapse-item
          class="title"
          :title="index == 0 ? '添加教练员（或队员）信息' : '添加队员信息'"
          :name="index"
        >
          <van-popup v-model="showAreaSelect" position="bottom">
            <van-area
              :area-list="areaList"
              @confirm="areaChange"
              @cancel="hideAreaSelect"
            />
          </van-popup>
          <van-cell-group>
            <van-cell title="姓名" class="cell">
              <template slot="">
                <van-field
                  class="input"
                  v-model="user.name"
                  maxlength="8"
                  placeholder="请输入姓名"
                  clearable
                  input-align="right"
                />
              </template>
            </van-cell>
            <van-cell title="年龄" class="cell">
              <template slot="">
                <van-field
                  class="input"
                  v-model="user.age"
                  readonly
                  @click="showpop(index)"
                  type="number"
                  maxlength="4"
                  placeholder="请输入年龄"
                  clearable
                  input-align="right"
                />
              </template>
            </van-cell>
            <van-cell title="性别" class="cell">
              <template slot="">
                <!-- <div class="select-box">
                  <div :class="{'activeSex': user.sex == '0'}" @click="selectSex(index,0)">
                    <i class="iconfont icon-nan "></i>
                    <span>男</span>
                  </div>
                  <div :class="{'activeSex' : user.sex == '1'}" style="margin-left: 0.5rem" @click="selectSex(index,1)">
                    <i class="iconfont icon-nv "></i>
                    <span>女</span>
                  </div>
                </div> -->
                <van-radio-group v-model="user.sex">
                  <van-radio
                    name="0"
                    checked-color="#42B572"
                    @click="selectSex(index, 0)"
                    >男</van-radio
                  >
                  <van-radio
                    name="1"
                    checked-color="#42B572"
                    @click="selectSex(index, 1)"
                    >女</van-radio
                  >
                </van-radio-group>
              </template>
            </van-cell>
            <van-cell title="手机号码" class="cell">
              <template slot="">
                <van-field
                  class="long-input"
                  v-model="user.phone"
                  maxlength="11"
                  placeholder="请输入手机号"
                  clearable
                  input-align="right"
                />
              </template>
            </van-cell>
            <van-cell title="证件号" class="cell">
              <template slot="">
                <van-field
                  class="long-input"
                  v-model="user.card"
                  maxlength="18"
                  clearable
                  placeholder="请输入"
                  input-align="right"
                />
              </template>
            </van-cell>
            <van-cell
              :title="item.name"
              class="cell"
              v-for="(item, index) in user.customize"
              :key="index"
            >
              <template slot="">
                <van-field
                  class="long-input"
                  v-model="item.value"
                  clearable
                  placeholder="请输入"
                  input-align="right"
                />
              </template>
            </van-cell>

            <van-cell title="职务" class="cell" v-if="index == 0">
              <template slot="">
                <van-radio-group v-model="user.post">
                  <van-radio
                    name="0"
                    checked-color="#42B572"
                    @click="selectPost(0)"
                    >教练</van-radio
                  >
                  <van-radio
                    name="1"
                    checked-color="#42B572"
                    @click="selectPost(1)"
                    >队员</van-radio
                  >
                </van-radio-group>
              </template>
            </van-cell>

            <van-cell title="团队名称" class="cell" v-if="index == 0">
              <template slot="">
                <van-field
                  class="long-input"
                  v-model="teamall_name"
                  clearable
                  placeholder="请输入团队名称"
                  input-align="right"
                />
              </template>
            </van-cell>
            <van-cell title="团队名称" class="cell" v-else>
              <template slot="">
                <div class="teamall_name">{{ teamall_name }}</div>
              </template>
            </van-cell>
            <div class="operation" v-if="operation">
              <div @click="addInfo()" class="addInfo">添加队友信息</div>
              <div @click="deleteInfo(index)" class="deleteInfo">
                删除当前信息
              </div>
            </div>
          </van-cell-group>
        </van-collapse-item>
      </div>
    </van-collapse>
    <div class="confirm" style="position: relative">
      <van-checkbox
        v-model="read"
        checked-color="#07c160"
        @change="readrule"
        style="position: absolute; left: 0.2rem; top: -0.2rem"
        >同意<span style="color: #42b574; text-decoration: underline"
          >《防疫提醒和报名须知》</span
        ></van-checkbox
      >
      <div class="confirmBtn" @click="confirmPay" v-if="!Pay">确认并缴费</div>
      <div v-if="Pay" class="pay-box">
        <div>
          支付：<span style="color: red" v-if="is_pay == 1">已支付</span>
          <span style="color: red" v-if="is_pay == 0">未支付</span>
        </div>
        <div class="pay-box-method">
          <div class="wechat" @click="weixinPay">微信支付</div>
        </div>
      </div>
    </div>
    <van-popup
      v-model="showrule"
      round
      :style="{ height: '60%', width: '80%' }"
      class="notice"
    >
      <div class="article" style="padding: 0.5rem; text-align: left">
        <h3 style="text-align: center; margin: 0.3rem 0">防疫提醒和报名须知</h3>
        {{ rule }}
      </div>
    </van-popup>
    <van-popup v-model="show" position="bottom" :style="{ height: '30%' }">
      <van-picker
        title="请选择年龄"
        show-toolbar
        :columns="columns"
        @confirm="onConfirm"
        @cancel="onCancel"
        @change="onChange"
        :loading="load"
        :swipe-duration="1500"
        ref="picker"
      />
    </van-popup>
    <van-dialog
      v-model="show_tip"
      :title="confirmTip"
      show-cancel-button
      @confirm="teamNameConfirm"
      @cancel="teamNameCancel"
    >
      <div></div>
    </van-dialog>
  </div>
</template>

<script>
import teamName from "./formTitle";
import formItem from "./formItem";
import areaList from "vant/packages/area/demo/area.js";
import { Toast } from "vant";
import { mapGetters, mapState } from "vuex";
export default {
  name: "teamHome",
  data() {
    return {
      confirmTip: "",
      show_tip: false,
      type: "",
      noread: true,
      showrule: false,
      read: "",
      rule: "",
      activeNames: [0],
      Pay: false,
      is_pay: null,
      // sign_info: [],
      com: null,
      areaList,
      show: false,
      columns: [],
      load: false,
      showAreaSelect: false,
      templetArr: [],
      arr: [],
      operation: true,
      sign_up_click: true,
      curindex: "0",
      teamall_name: "",
    };
  },
  components: {
    teamName,
    formItem,
  },
  computed: {
    ...mapGetters(["GET_SEX"]),
  },
  created() {
    this.rule =
      "（一）为配合疫情防控要求，本次赛事需遵守地方防疫政策。（二）所有参赛选手须在报名前确定“健康码”须符合比赛地健康码“绿码”且体温正常（37.3℃以下），无相关症状（干咳、乏力、咽痛、腹泻）的要求方可报名参赛。（三）比赛当天参赛选手“健康码”需为绿码且健康状况正常，须科学佩戴口罩（比赛期间可不佩带），赛前检录经测量体温正常（37.3℃以下），方可进入集结区及各功能区。（四）既往新冠肺炎确诊病例、疑似病例、无症状感染者及其密切接触者、确诊病例处于出院后的隔离医学观察期、无症状感染者处于解除隔离治疗或集中隔离医学观察后的医学观察随访期、入境后集中隔离医学观察期、不能提供相关证明材料等情况的人员，不得参加比赛。（五）所有的参赛选手都须遵从赛事组委会的防疫要求，否则将取消参赛资格。（六）如国内疫情出现新的变化，组委会将根据新的疫情防控要求对赛事做进一步调整";
    this.sign_up_info();
    this.setAge();
    console.log(this.templetArr);
  },
  methods: {
    teamNameConfirm() {
      this.upConfirm()
    },
    teamNameCancel() {
      this.sign_up_click = true
      console.log("重新输入团队名称");
    },
    // 选择教练员或者领队
    selectPost(type) {
      this.type = type;
    },
    // 阅读报名须知
    readrule() {
      this.showrule = true;
      this.noread = !this.noread;
    },
    showpop(index) {
      this.curindex = index;
      this.show = true;
      setTimeout(() => {
        this.$refs.picker.setColumnIndex(0, 14);
      }, 100);
    },
    setAge() {
      this.load = true;
      // let age = 4+(Math.random()*94-4)
      var arr = [];
      for (var i = 4; i <= 90; i++) {
        arr.push(i.toString());
      }
      this.columns = arr;
      this.load = false;
    },
    onConfirm(value, index) {
      // Toast(`当前值：${value}, 当前索引：${index}`);
      this.show = false;
      this.templetArr[this.curindex].age = value;
    },
    onChange(picker, value, index) {
      // Toast(`当前值：${value}, 当前索引：${index}`);
      this.templetArr[this.curindex].age = value;
      // console.log(this.user.age)
    },
    onCancel() {
      // Toast('取消');
      this.show = false;
    },
    addInfo() {
      let templetArr = this.createdObg();
      for (var i = 0; i < templetArr.length; i++) {
        for (var j = 0; j < this.arr.length; j++) {
          templetArr[i].customize.push({
            name: this.arr[j],
            value: "",
          });
        }
      }
      this.templetArr.push(templetArr[0]);
    },
    deleteInfo(index) {
      if (index > 1) {
        this.templetArr.splice(index, 1);
      } else {
        this.$toast("团体报名人数不能少于2人！");
      }
    },
    userInfo() {
      this.$axios
        .get("/mobile/v1/PersonalCenter/my_info", {
          headers: {
            token: window.sessionStorage.getItem("token"),
          },
        })
        .then((res) => {
          if (res.data.code == 2000) {
            this.templetArr[0].name = res.data.data.user_info.name;
            this.templetArr[0].age = res.data.data.user_info.age;
            // this.templetArr[0].sex = res.data.data.user_info.sex
            this.templetArr[0].phone = res.data.data.user_info.phone;
            this.templetArr[0].card = res.data.data.user_info.id_card;
          }
        })
        .catch((res) => {
          //console.log(res.msg);
        });
    },
    checkedItem() {
      let flag = true;
      for (var i = 0; i < this.templetArr.length; i++) {
        this.templetArr[i].team_name = this.teamall_name;
        for (var key in this.templetArr[i]) {
          if (!this.templetArr[i][key] && this.templetArr[i][key] != "0") {
            return false;
          }
        }
      }
      return flag;
    },
    confirmPay() {
      if (this.checkedItem()) {
        //  && this.type !== ""
        if (this.sign_up_click) {
          this.sign_up_click = false;
          let str = JSON.stringify(this.templetArr);
          let arr = JSON.parse(str);
          for (var i = 0; i < arr.length; i++) {
            for (var j = 0; j < arr[i].customize.length; j++) {
              arr[i].customize[j] = arr[i].customize[j].value;
            }
          }
          for (var i = 0; i < arr.length; i++) {
            arr[i].customize = arr[i].customize.join(",");
          }
          console.log(arr);
          let matchType = this.$route.query.projectType;
          if (matchType.indexOf("男") != "-1") {
            console.log("该比赛仅限男性运动员参加");
            if (arr[0].sex == 1 || arr[1].sex == 1) {
              this.$toast("该比赛仅限男性运动员参加");
              return;
            }
          } else if (matchType.indexOf("女") != "-1") {
            console.log("该比赛仅限女性运动员参加");
            if (arr[0].sex == 0 || arr[1].sex == 0) {
              this.$toast("该比赛仅限女性运动员参加");
              return;
            }
          } 
          if (this.noread) {
            Toast("请先同意防疫提醒和报名须知");
            return;
          }
            this.$axios.post(
              "/mobile/v1/apply/sign_up",
              {
                is_confirm:0,
                sign: arr,
                project_id: this.$route.query.project_id,
                com_id: this.$route.query.com_id,
                group_type: this.$route.query.projectType,
              },
              {
                headers: {
                  token: window.sessionStorage.getItem("token"),
                },
              }
            )
            .then((res) => {
               if (res.data.code == 200) {
                this.operation = false;
                this.Pay = true;
                this.$toast(res.data.msg);
              }
              if (res.data.code == 400) {
                setTimeout(() => {
                  this.sign_up_click = true;
                }, 3000);
                this.$toast(res.data.msg);
              }
              console.log(res);
              if (res.data.code == 201) {  
                this.confirmTip = res.data.msg;
                this.show_tip = true;
                this.sign_up_click = true
              }
              else{
                // this.sign_up_click = true
                // this.upConfirm()
              }
            }
            )
            .catch((err) => {
              console.log(err);
            });
            
        } else {
          this.sign_up_click = true;
          this.$axios("请不要重复点击");
        }
      } else {
        this.$toast("请填写完整信息!")
        return;
      }
    },

    upConfirm(){
      if (this.checkedItem()) {
        if (this.sign_up_click) {
          this.sign_up_click = false;
          let str = JSON.stringify(this.templetArr);
          let arr = JSON.parse(str);
          for (var i = 0; i < arr.length; i++) {
            for (var j = 0; j < arr[i].customize.length; j++) {
              arr[i].customize[j] = arr[i].customize[j].value;
            }
          }
          for (var i = 0; i < arr.length; i++) {
            arr[i].customize = arr[i].customize.join(",");
          }
          console.log(arr);
          let matchType = this.$route.query.projectType;
          if (matchType.indexOf("男") != "-1") {
            console.log("该比赛仅限男性运动员参加");
            if (arr[0].sex == 1 || arr[1].sex == 1) {
              this.$toast("该比赛仅限男性运动员参加");
              return;
            }
          } else if (matchType.indexOf("女") != "-1") {
            console.log("该比赛仅限女性运动员参加");
            if (arr[0].sex == 0 || arr[1].sex == 0) {
              this.$toast("该比赛仅限女性运动员参加");
              return;
            }
          } 
          if (this.noread) {
            Toast("请先同意防疫提醒和报名须知");
            return;
          }
      this.$axios.post(
              "/mobile/v1/apply/sign_up",
              {
                 is_confirm:1,
                sign: arr,
                project_id: this.$route.query.project_id,
                com_id: this.$route.query.com_id,
                group_type: this.$route.query.projectType,
              },
              {
                headers: {
                  token: window.sessionStorage.getItem("token"),
                },
              }
            )
            .then((res) => {
              if (res.data.code == 200) {
                this.operation = false;
                this.Pay = true;
                this.$toast(res.data.msg);
              }
              if (res.data.code == 400) {
                setTimeout(() => {
                  this.sign_up_click = true;
                }, 3000);
                this.$toast(res.data.msg);
              }
            })
            .catch((res) => {});
    }}},

    createdObg() {
      let item = 2;
      let newObj = [];
      for (let i = 0; i < item; i++) {
        newObj[i] = {
          name: "",
          age: "",
          sex: "",
          phone: "",
          card: "",
          regist_num: "1",
          team_name: this.teamall_name,
          customize: [],
          post: "1",
        };
      }
      return newObj;
    },
    sign_up_info() {
      this.$axios
        .get("/mobile/v1/apply/sign_up_info", {
          params: {
            project_id: this.$route.query.project_id,
          },
          headers: {
            token: window.sessionStorage.getItem("token"),
          },
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.is_pay = res.data.data.is_pay;
            this.$axios
              .get("/mobile/v1/apply/sign_up", {
                params: {
                  group_id: this.$route.query.project_id,
                  group_type: this.$route.query.projectType,
                },
                headers: {
                  token: window.sessionStorage.getItem("token"),
                },
              })
              .then((res) => {
                if ((res.data.code = 200)) {
                  let templetArr = this.createdObg();
                  let arr = [];
                  arr = res.data.data.data.get_com.require.slice(6);
                  this.arr = arr;
                  for (var i = 0; i < templetArr.length; i++) {
                    for (var j = 0; j < arr.length; j++) {
                      templetArr[i].customize.push({
                        name: arr[j],
                        value: "",
                      });
                    }
                  }
                  this.templetArr = templetArr;
                  console.log(templetArr);
                  this.userInfo();
                }
              })
              .catch((res) => {
                //  console.log(res.msg);
              });
          } else {
          }
        })
        .catch((res) => {
          //  console.log(res.msg);
        });
    },
    weixinPay() {
      // var params = new URLSearchParams();
      // params.append('project_id', this.$route.query.project_id);
      this.$axios
        .get("/mobile/v1/Orderpay/wx_pay", {
          params: {
            project_id: this.$route.query.project_id,
          },
          headers: {
            token: window.sessionStorage.getItem("token"),
          },
        })
        .then((res) => {
          if (res.data.code == 2000) {
            this.weixinPays(res.data.data);
          } else {
            Toast(res.data.message);
          }
        })
        .catch((res) => {
          //  console.log(res.msg);
        });
    },
    weixinPays(data) {
      var vm = this;
      if (typeof WeixinJSBridge == "undefined") {
        //微信浏览器内置对象。参考微信官方文档
        console.log("not wx");
        if (document.addEventListener) {
          document.addEventListener(
            "WeixinJSBridgeReady",
            vm.onBridgeReady(data),
            false
          );
        } else if (document.attachEvent) {
          document.attachEvent("WeixinJSBridgeReady", vm.onBridgeReady(data));
          document.attachEvent("onWeixinJSBridgeReady", vm.onBridgeReady(data));
        }
      } else {
        vm.onBridgeReady(data);
      }
    },
    onBridgeReady(data) {
      var vm = this;
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: data.appId, //公众号名称，由商户传入
          timeStamp: data.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: data.nonceStr, //随机串
          package: data.package,
          signType: data.signType, //微信签名方式：
          paySign: data.paySign, //微信签名
        },
        function (res) {
          // alert(JSON.stringify(res))
          // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            vm.$toast("支付成功");
            vm.is_pay = 1;
            vm.$router.push({
              path: "/mine/match",
            });
          } else {
            vm.$toast("支付失败");
          }
        }
      );
    },
    selectSex(index, type) {
      if (this.templetArr[index].sex == type) {
      } else {
        this.templetArr[index].sex = type;
      }
      console.log(this.templetArr[index].sex);
    },
    areaChange(value) {
      console.log(value);
      this.showAreaSelect = false;
      this.user.province = `${value[0].name} ${value[1].name} ${value[2].name}`;
    },
    hideAreaSelect() {
      this.showAreaSelect = false;
    },
    changePhone() {},
  },
};
</script>

<style lang="less" scoped>
/deep/ .notice {
  border-radius: 10px;
}
.van-radio {
  display: inline-block;
  margin-right: 5px;
}
.operation {
  display: flex;
  justify-content: center;
  margin-top: 15px;

  div {
    padding: 0.1rem 0.2rem;
    margin: 0.1rem 0.2rem;
    // border: 1px #ebedf0 solid;
  }

  .addInfo {
    color: #37bb72;
    border: 1px solid #37bb72;
  }

  .deleteInfo {
    color: red;
    border: 1px solid red;
  }
}

.title {
  text-align: left;
}

.confirm {
  display: flex;
  justify-content: center;
  margin-top: 0.4rem;
}

.confirmBtn {
  margin: 1rem 0;
  width: 2rem;
  background: #42b574;
  color: #fff;
  height: 0.8rem;
  line-height: 0.8rem;
  font-size: 0.32rem;
}

.pay-box {
  margin: 0.3rem;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  height: 2rem;
  width: 100%;
  align-items: flex-start;
  font-size: 0.3rem;
  font-weight: bold;
}

.pay-box-method {
  display: flex;
  height: 0.7rem;
  line-height: 0.7rem;
  width: 2rem;
  margin: 0 auto;

  .wechat {
    color: #fff;
    width: 2rem;
    background: #1ea65a;
    // 			margin-right: 0.6rem;
    // 			margin-left: 0.2rem;
  }

  .alipay {
    color: #fff;
    width: 1.8rem;
    background: #1891e0;
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter,
  .fade-leave-to

  /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}

.cell {
  text-align: left;

  .select-box {
    display: flex;
    justify-content: flex-end;
  }

  .iconfont {
    margin-right: 0.1rem;
    font-size: 0.34rem;
  }

  .activeSex {
    color: #42b574;
  }
}

.input {
  padding: 0;
  float: right;
  width: 2rem;
}

.short-input {
  padding: 0;
  float: right;
  width: 1rem;
}

.long-input {
  padding: 0;
  float: right;
  width: 3rem;
}
.teamall_name {
  width: 150px;
  height: 24px;
  line-height: 24px;
  text-align: right;
  margin-left: 2.133vw;
  overflow: hidden;
}
</style>
